package by.dkusch.aircompany.webapp.page.base.validator;

import javax.inject.Inject;
import javax.persistence.metamodel.SingularAttribute;

import org.apache.wicket.injection.Injector;
import org.apache.wicket.validation.IValidatable;
import org.apache.wicket.validation.IValidator;
import org.apache.wicket.validation.ValidationError;

import by.dkusch.aircompany.model.tables.UserAccount;
import by.dkusch.aircompany.services.UserService;

public class UniqueUserEmailValidator implements IValidator<String> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	SingularAttribute<UserAccount, String> attr;
	UserAccount entity;

	@Inject
	UserService userService;

	public UniqueUserEmailValidator(SingularAttribute<UserAccount, String> attr, UserAccount entity) {
		Injector.get().inject(this);
		this.attr = attr;
		this.entity = entity;
	}

	@Override
	public void validate(IValidatable<String> validatable) {
		final String field = validatable.getValue();

		if (!userService.checkUniqueAccountFields(attr, field, entity == null ? null : entity.getId())) {
			error(validatable, "error.field.notunique");
		}

	}

	protected void error(IValidatable<String> validatable, String errorKey) {
		ValidationError error = new ValidationError();
		error.addKey(getClass().getSimpleName() + "." + errorKey);
		validatable.error(error);
	}

}
